/* eslint-disable array-callback-return */
/* eslint-disable no-param-reassign */
import {
  getSystemList,
  getRoleDetail,
  fetchTreeData,
  updateSubmit,
  insertSubmit,
  listBaseSys,
  getBaseRole,
} from '@/services/permissionmanage';
import { message } from 'antd';
import { routerRedux } from 'dva/router';

export default {
  state: {
    systemList: [],
    roleInfo: {},
    treeData: [],
    checkedKeys: [],
    expandedKeys: [],
  },
  effects: {
    // 获取系统列表
    *fetchSystemList({ payload }, { call, put }) {
      const response = yield call(getSystemList, payload);
      if (response.success) {
        yield put({
          type: 'getSystemList',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '服务端错误'}`);
      }
    },
    // 获取详情数据
    *fetchDetail({ payload }, { call, put }) {
      const response = yield call(getRoleDetail, payload);
      if (response.success) {
        yield put({
          type: 'fetchTreeData',
          payload: { sysId: response.data.sysId },
        });
        yield put({
          type: 'getDetail',
          payload: response.data,
        });
      } else {
        const state = {
          systemList: [],
          roleInfo: {},
          treeData: [],
          checkedKeys: [],
          expandedKeys: [],
        };
        yield put({
          type: 'updateModelData',
          payload: { ...state },
        });
        message.warning(`${response.message || '服务端错误'}`);
      }
    },

    // 树形结构数据
    *fetchTreeData({ payload }, { call, put }) {
      const response = yield call(fetchTreeData, payload);
      if (response.success) {
        yield put({
          type: 'getTreeData',
          payload: { data: response.data },
        });
      } else {
        message.warning(`${response.message || '获取授权菜单：服务端错误'}`);
      }
    },

    // 提交数据
    *submit({ payload }, { call, put, select }) {
      const formValues = payload.values;
      const treeData = yield select(state => state.role.treeData);
      const baseRoleVo = [];
      const getSubmitBaseRoleVo = data => {
        // 获取提交数据的baseRoleVo集合
        data.forEach(item => {
          if (formValues.baseRoleVo.some(id => id === item.functionId)) {
            baseRoleVo.push({
              functionId: item.functionId,
              sysId: item.item || formValues.sysId,
              parentId: item.parentId || null,
              functionType: item.functionType,
            });
          }
          if (Object.keys(item).includes('childs')) {
            getSubmitBaseRoleVo(item.childs);
          }
        });
      };
      getSubmitBaseRoleVo(treeData);
      delete formValues.baseRoleVo;
      const submitData = payload.roleId
        ? { ...formValues, baseRoleVo, roleId: payload.roleId }
        : { ...formValues, baseRoleVo };
      const response = yield call(payload.roleId ? updateSubmit : insertSubmit, submitData);
      if (response.success) {
        const state = {
          systemList: [],
          roleInfo: {},
          treeData: [],
          checkedKeys: [],
          expandedKeys: [],
        };
        yield put({
          type: 'updateModelData',
          payload: { ...state },
        });
        message.success(payload.roleId ? '保存成功!' : '新增成功！');
        yield put(
          routerRedux.push({
            pathname: '/systemmanage/role/index',
          })
        );
      } else {
        message.warning(`${response.message || '保存失败！'}`);
      }
    },
    *listBaseSys({ payload }, { call }) {
      const response = yield call(listBaseSys, payload);
      return response;
    },
    *getBaseRole({ payload }, { call }) {
      const response = yield call(getBaseRole, payload);
      return response;
    },
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取系统列表
    getSystemList(state, { payload }) {
      return {
        ...state,
        systemList: payload,
      };
    },

    // 获取详情
    getDetail(state, { payload }) {
      const expandedKeys = [];
      const checkedKeys = [];
      if (payload.baseFunction.length) {
        const getCheckedId = treeData => {
          treeData.forEach(item => {
            if (Object.keys(item).includes('childs')) {
              getCheckedId(item.childs);
              expandedKeys.push(item.functionId);
            } else {
              checkedKeys.push(item.functionId);
            }
          });
        };
        getCheckedId(payload.baseFunction);
      }

      return {
        ...state,
        roleInfo: payload,
        checkedKeys,
        expandedKeys,
      };
    },

    // 组装树形数据
    getTreeData(
      state,
      {
        payload: { data },
      }
    ) {
      let newTreeData = [];
      const toTreeData = treeData => {
        const arr = [...treeData];
        arr.map(item => {
          item.key = item.functionId;
          item.title = item.functionName;
          item.isLeaf = item.functionType === 2;
          if (Object.keys(item).includes('childs')) {
            item.children = item.childs;
            toTreeData(item.childs);
          }
        });
        return arr;
      };
      newTreeData = [...toTreeData(data)];

      return {
        ...state,
        treeData: newTreeData,
      };
    },
  },
};
